package com.cms.process;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
 
import com.cms.common.StringUtils;
import com.cms.constant.CmsConstant;
import com.google.common.collect.Maps;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


@Component(value="cmsFreemarkerProcess")
public class FreemarkerProcess {


	@Autowired
	private Configuration conf;
	
	/***
	 * 
	 * @param template
	 * @param model
	 * @return
	 * @throws IOException
	 * @throws TemplateException
	 */
	public  String processTemplateIntoString(Template template,
			Map<String, Object> model) throws IOException, TemplateException {
		//model.putAll(StringUtils.addEnv());
		StringWriter result = new StringWriter();
		template.process(model, result);
		return result.toString();
	}

	/***
	 * 
	 * @param name
	 * @param content
	 * @return
	 * @throws Exception
	 */
	public  String buildTemplateHeader(String name, String content)
			throws Exception {
	 
		Template template = new Template(name+"_Header", new StringReader(content), conf);
		Map<String, Object> rootMap =Maps.newHashMap();
		StringWriter result = new StringWriter();
		template.process(rootMap, result);
		return result.toString();
	}
	
	
	/***
	 * 
	 * @param name
	 * @param content
	 * @return
	 * @throws Exception
	 */
	public  String buildTemplateFoot(String name, String content)
			throws Exception {
		if(StringUtils.isBlank(content))
		{
			return StringUtils.EMPTY;
		} 
		Template template = new Template(name+"_FOOT", new StringReader(content), conf);
		Map<String, Object> rootMap = Maps.newHashMap();
		StringWriter result = new StringWriter();
		template.process(rootMap, result);
		return result.toString();
	}

	/***
	 * 
	 * @param name
	 * @param content
	 * @return
	 * @throws Exception
	 */
	public String buildTemplateBody(String name,String reportSummary ,String content,ModelMap data)
			throws Exception { 
		StringBuilder sb = new StringBuilder();
		if(!StringUtils.isBlank(reportSummary))
		{
			 sb.append(reportSummary);
		}
		sb.append(CmsConstant.PAGING_PREFIX);
		sb.append(content);
		sb.append(CmsConstant.PAGING_STUFFIX);
		Template template = new Template(name+"_Body", new StringReader(sb.toString()), conf);
		StringWriter result = new StringWriter();
		template.process(data, result);
		return result.toString();
	}

}
